<?php
/**
 * @Author: Xu Liu email:2867557054@qq.com
 * @Date:   2016-12-15 13:31:33
 * @Last Modified by:   Xu Liu
 * @Last Modified time: 2018-02-24 16:18:13
 */
if (!defined('IN_DISCUZ')) {
    exit('Access Denied');
}
class TouchauthorContrl
{
    public function __construct()
    {
        global $_G;
        !allowpostbook() && showmessage(lang('plugin/jameson_read', 'wuquanfabu'));
        $_G['jameson_read']['booksnum']    = C::t('#jameson_read#jamesonread_books')->count_by_uid($_G['uid']);
        $_G['jameson_read']['topbooksnum'] = C::t('#jameson_read#jamesonread_books')->counttop_by_uid($_G['uid']);
        $_G['jameson_read']['piaos']       = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
    }
    public function index()
    {
        global $_G;
        $jamesonread_title = lang("plugin/jameson_read", "zuozhezhongxin");
        require_once './source/plugin/jameson_read/class/Page.class.php';
        $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        if(!$authorinfo){
            $authorinfo = array(
                'author_id'   => $_G['uid'],
                'groupid'   => $_G['groupid'],
                'status'      => 1,
                'edit'        => 1,
                'allowedit'   => 1,
                'tuijianpiao' => 0,
                'yuepiao' => 0,
                'cuigengpiao' => 0,
                'zgsj' => 0,
                'qzsj' => 0,
                'setsj' => 'zgsj',
            );
            C::t('#jameson_read#jamesonread_authors')->insert($authorinfo);
        }
        $page       = new Page($_G['jameson_read']['booksnum'], 20, './plugin.php?id=jameson_read&contrl=touchauthor&act=index');
        $books      = C::t('#jameson_read#jamesonread_books')->fetch_by_uid($_G['uid'], $page->getStart(), $page->getSize(), 1);
        $pageshow   = $page->showweui();
        $dibunav = C::t('#jameson_read#jamesonread_topics')->fetch_by_type(120);
        $navtitle = lang('plugin/jameson_read','zuozhezhongxin').'_'.$_G['setting']['bbname'];
        include template("jameson_read:touch/authorindex");
    }
    public function bookedit()
    {
        global $_G;
        C::t('#jameson_read#jamesonread_books')->clear_cache(array($_GET['book_id'] . '_' . $_G['uid']));
        $books      = array();
        $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        $books      = C::t('#jameson_read#jamesonread_books')->fetchAllInfoById($_GET['book_id']);
        if (!$books['fenjuan']) {
            $tmpjuan = array(
                'j_title'   => lang('plugin/jameson_read', 'diyijuan'),
                'book_id'   => $books['book_id'],
                'order_num' => 1,
            );
            $tmpjuan['j_id']                    = C::t('#jameson_read#jamesonread_fenjuan')->insert($tmpjuan, true);
            $books['fenjuan'][$tmpjuan['j_id']] = $tmpjuan;
        }
        $jamesonread_title  = $books['book_name'] . '[' . lang('plugin/jameson_read', 'bianji') . ']';
        $books['categorys'] = C::t('#jameson_read#jamesonread_categorys')->fetch_all_parent(0);
        $books['childcate'] = C::t('#jamesonread_read#jamesonread_categorys')->fetch_all_parent($books['parent_id']);
        $navtitle = $books['book_name'].'_'.lang('plugin/jameson_read','zuozhezhongxin').'_'.$_G['setting']['bbname'];
        include template("jameson_read:touch/authorbookedit");
    }
    public function bookadd()
    {
        global $_G;
        $books      = array();
        $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        if (!$authorinfo['status']) {
            // 如果被禁止发布图书
            showmessage(lang('plugin/jameson_read', 'wuquanfabu'), dreferer());
        }
        $book_id            = 0;
        $navtitle           = $jamesonread_title           = lang('plugin/jameson_read', 'tianjiaxinshu');
        $books['categorys'] = C::t('#jameson_read#jamesonread_categorys')->fetch_all_parent(0);
        $tmp = current($books['categorys']);
        $books['parent_id'] = $tmp['category_id']; 
        $books['childcate'] = C::t('#jamesonread_read#jamesonread_categorys')->fetch_all_parent($books['parent_id']);
        $action             = 'add';
        $navtitle = lang('plugin/jameson_read','tianjiaxinshu').'_'.lang('plugin/jameson_read','zuozhezhongxin').'_'.$_G['setting']['bbname'];
        include template("jameson_read:touch/authorbookadd");
    }
    public function postbook()
    {
        global $_G;

        if ($_GET['formhash'] != FORMHASH) {
            echo 'Error:'.lang('plugin/jameson_read', 'laiyuanfeifa');
            exit;
        }
        $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        if (!$_GET['book_id'] && !$authorinfo['status']) {
            // 如果被禁止发布图书
            echo 'Error:'.lang('plugin/jameson_read', 'wuquanfabu');
            exit;
        }
        $book_id             = intval($_GET['book_id']);
        $data                = array();
        $data['author']      = daddslashes(dhtmlspecialchars(trim($_GET['author'])));
        $data['book_name']   = daddslashes(dhtmlspecialchars(trim($_GET['book_name'])));
        $data['desco']   = daddslashes(dhtmlspecialchars(trim($_GET['desco'])));
        $data['category_id'] = intval($_GET['category_id']);
        $data['parent_id']   = intval($_GET['parent_id']);
        if (strtolower($_G['charset']) == 'gbk') {
            $data['author'] = xfxs_isutf($data['author'])?diconv($data['author'], 'utf-8', 'gbk'):$data['author'];
            $data['desco'] = xfxs_isutf($data['desco'])?diconv($data['desco'], 'utf-8', 'gbk'):$data['desco'];
            $data['book_name'] = xfxs_isutf($data['book_name'])?diconv($data['book_name'], 'utf-8', 'gbk'):$data['book_name'];
        } else if (strtolower($_G['charset']) == 'utf-8') {
            $data['author'] = !xfxs_isutf($data['author'])?diconv($data['author'], 'GB2312', 'utf-8'):$data['author'];
            $data['desco'] = !xfxs_isutf($data['desco'])?diconv($data['desco'], 'GB2312', 'utf-8'):$data['desco'];
            $data['book_name'] = !xfxs_isutf($data['book_name'])?diconv($data['book_name'], 'GB2312', 'utf-8'):$data['book_name'];
        }
            $data['addtime']   = TIMESTAMP;
            $data['uid']       = intval($_G['uid']);
            if(!$data['desco']){
                unset($data['desco']);
            }
            $data['plan']      = $_GET['plan']?1:0;
        $res = false;
        if (isset($_FILES['imgname'])) {
            $upload = new discuz_upload();
            $upload->init($_FILES['imgname'], 'forum');
            if ($upload->is_image_ext($upload->fileext($_FILES['imgname']['name']))) {
                if ($upload->save()) {
                    $data['image'] = $upload->attach['attachment'];
                }
            }
            unset($upload);
        }
        if ($book_id) {
            $res = C::t('#jameson_read#jamesonread_books')->update($book_id, $data);
            C::t('#jameson_read#jamesonread_books')->clear_cache(array($book_id . '_0', $book_id . '_' . $_G['uid']));
        } else {
            $res = $book_id = C::t('#jameson_read#jamesonread_books')->insert($data, true);
            if ($res) {
                C::t('#jameson_read#jamesonread_fenjuan')->insert(array(
                    'order_num' => 1,
                    'j_title'   => lang('plugin/jameson_read', 'weifenjuan'),
                    'book_id'   => $book_id,
                ));
                if (!DB::result_first('SELECT count(*) FROM %t WHERE author_id=%d', array('jamesonread_authors', $_G['uid']))) {
                    C::t('#jameson_read#jamesonread_authors')->insert(array(
                        'author_id'   => $_G['uid'],
                        'status'      => 1,
                        'edit'        => 1,
                        'allowedit'   => 1,
                        'tuijianpiao' => 0,
                        'yuepiao' => 0,
                        'cuigengpiao' => 0,
                        'zgsj' => 0,
                        'qzsj' => 0,
                        'setsj' => 'zgsj',
                    ));
                }
            } else {
                echo 'Error:'.lang('plugin/jameson_read', 'caozuoshibai');
                exit;
            }
        }
        C::t('#jameson_read#jamesonread_books')->clear_cache(array("bookinfo-".$book_id."-".$_G['uid'], "bookinfo-".$book_id."-0"));
        echo './plugin.php?id=jameson_read&contrl=touchauthor&act=bookedit&book_id=' . $book_id;
    }
    public function postfenjuan()
    {
        global $_G;
        if ($_GET['formhash'] != FORMHASH) {
            showmessage(lang('plugin/jameson_read', 'laiyuanfeifa'));
        }
        $book_id = intval($_GET['book_id']);
        foreach ($_GET['fenjuanname'] as $key => $value) {
            $dataup = array();
            if (!trim($value)) {
                continue;
            }
            $dataup['j_title'] = daddslashes(dhtmlspecialchars($value));
            $dataup['book_id'] = $book_id;
            C::t('#jameson_read#jamesonread_fenjuan')->update($key, $dataup);
        }
        $oldnum = (int) DB::result_first('SELECT order_num FROM %t WHERE book_id=%d ORDER BY order_num DESC', array('jamesonread_fenjuan', $book_id));

        if ($_GET['newfenjuanname']) {
            $data = array();
            $oldnum++;
            $data['order_num'] = $oldnum;
            $data['j_title']   = daddslashes(dhtmlspecialchars($_GET['newfenjuanname']));
            $data['book_id']   = $book_id;
            C::t('#jameson_read#jamesonread_fenjuan')->insert($data);
        }
        C::t('#jameson_read#jamesonread_fenjuan')->clear_cache(array('by' . $book_id, 'all' . $book_id));
        C::t('#jameson_read#jamesonread_books')->clear_cache(array("bookinfo-".$book_id."-".$_G['uid'], "bookinfo-".$book_id."-0"));
        showmessage(lang('plugin/jameson_read', 'gengxinchenggong'), './plugin.php?id=jameson_read&contrl=touchauthor&act=bookedit&book_id=' . $book_id . '&forward=fenjuanguanli');
    }
    public function postzhangjie()
    {
        global $_G;
        if (FORMHASH != trim($_GET['formhash'])) {
            echo 'Error:'.lang('plugin/jameson_read', 'laiyuanfeifa');
            exit;
        }
        $data                = array();
        $data['colum_id']    = intval($_GET['colum_id']);
        $data['tid']         = intval($_GET['tid']);
        $data['book_id']     = intval($_GET['book_id']);
        $data['subject']     = urldecode($_GET['subject']);
        $message    = urldecode($_GET['message']);
        if (strtolower($_G['charset']) == 'gbk') {
            $data['subject'] = xfxs_isutf($_GET['subject'])?diconv($data['subject'], 'utf-8', 'gbk'):$data['subject'];
            $message = xfxs_isutf($_GET['message'])?diconv($message, 'utf-8', 'gbk'):$message;
        } else if (strtolower($_G['charset']) == 'utf-8') {
            $data['subject'] = !xfxs_isutf($_GET['subject'])?diconv($data['subject'], "GB2312", 'utf-8'):$data['subject'];
            $message = !xfxs_isutf($_GET['message'])?diconv($message, "GB2312", 'utf-8'):$message;
        }
        $message = nl2br($message);
        $message = preg_replace(
        array(
            "/(<\w+[^>]*?\s)on(\w+)/ism"
         ),
        array(
            '\1 \2'
        ), $message);
        $data['length']      = intval($_GET['youxiaozishu']);
        $data['j_id']        = intval($_GET['j_id']);
        $data['category_id'] = intval($_GET['category_id']);
        $books = C::t('#jameson_read#jamesonread_books')->fetch($data['book_id']);
        if (isset($_GET['price'])) {
            $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
            if ($authorinfo[$authorinfo['setsj']]) {
                if($authorinfo['setsj']=='zgsj'){
                    $data['price'] = intval($_GET['price']) > $authorinfo['zgsj'] ? $authorinfo['zgsj'] : intval($_GET['price']);
                }else{
                    $data['price'] = intval($_GET['price']);
                }
            } else {
                $data['price'] = 0;
            }
        }
        if ($data['colum_id'] && $data['tid']) {
            // 更新
            $threadata = array(
                'fid'      => intval($_G['jameson_read']['fid']),
                'subject'  => $data['subject'],
                'dateline' => TIMESTAMP,
                'lastpost' => TIMESTAMP,
                'special'  => 127,
                'status'   => 544,
            );
            if (isset($data['pice'])) {
                $threadata['price'] = $data['price'];
            }
            $oldcol = C::t('#jameson_read#jamesonread_colums')->fetch($data['colum_id']);
            C::t("forum_thread")->update($data['tid'], $threadata);
            C::t('forum_post')->update('tid:'.$data['tid'],$oldcol['pid'],
                array(
                    'subject' => $data['subject'],
                    'message' => $message,
                )
            );
            C::t('#jameson_read#jamesonread_colums')->update($data['colum_id'], $data);
            C::t('#jameson_read#jamesonread_books')->update($data['book_id'],
                array(
                    'zishu' => $books['zishu'] + $data['length'] - $oldcol['length'],
                )
            );
        } else {
            // 插入
            $data['tid'] = C::t("forum_thread")->insert(array(
                'fid'        => intval($_G['jameson_read']['fid']),
                'author'     => $_G['username'],
                'authorid'   => $_G['uid'],
                'subject'    => $data['subject'],
                'dateline'   => TIMESTAMP,
                'lastpost'   => TIMESTAMP,
                'lastposter' => $_G['username'],
                'special'    => 127,
                'status'     => 544,
                'price'      => $data['price'],
            ), true);
            $pid = C::t('forum_post_tableid')->insert(array('pid' => ''), true);
            C::t('forum_post')->insert('tid:'.$data['tid'], array(
                'tid'       => $data['tid'],
                'pid'       => $pid,
                'fid'       => intval($_G['jameson_read']['fid']),
                'first'     => 1,
                'author'    => $_G['username'],
                'authorid'  => $_G['uid'],
                'subject'   => $data['subject'],
                'message'   => $message,
                'dateline'  => TIMESTAMP,
                'useip'     => $_G['clientip'],
                'port'      => $_SERVER['REMOTE_PORT'],
                'bbcodeoff' => -1,
                'smileyoff' => -1,
                'position'  => 1,
            ), true);
            $data['zhangjie'] = 1 + C::t("#jameson_read#jamesonread_colums")->fetch_by_bid($data['book_id']);
            $data['colum_id'] = C::t('#jameson_read#jamesonread_colums')->insert(array(
                'book_id'     => $data['book_id'],
                'category_id' => $data['category_id'],
                'uid'         => $_G['uid'],
                'fid'         => intval($_G['jameson_read']['fid']),
                'tid'         => $data['tid'],
                'pid'         => $pid,
                'zhangjie'    => $data['zhangjie'],
                'addtime'     => TIMESTAMP,
                'j_id'        => $data['j_id'],
                'subject'     => $data['subject'],
                'price'       => $data['price'],
                'length'      => $data['length'],
            ), true);
            $old = DB::fetch_first('SELECT zishu,hascol FROM %t WHERE book_id=%d', array('jamesonread_books', $data['book_id']));
            C::t('#jameson_read#jamesonread_books')->update($data['book_id'],
                array(
                    'zishu'  => ($old['zishu'] + $data['length']),
                    'hascol' => 1 + $old['hascol'],
                )
            );
            C::t('#jameson_read#jamesonread_update')->add(array(
                'book_id'=>$data['book_id'],
                'tid'=>$data['tid'],
                'pid'=>$pid,
                'category_id'=>$books['category_id'],
                'book_name'=>$books['book_name'],
                'subject'=>$data['subject'],
                'author'=>$books['author'],
                'addtime'=>TIMESTAMP,
                'parent_id'=>$books['parent_id'],
                'image'=>$books['image'],
            ));
            DB::query('UPDATE ' . DB::table('forum_forum') . ' SET ' . DB::field('todayposts', '1', '+') . ' WHERE ' . DB::field('fid', $_G['jameson_read']['fid']));
            // 如果发表文章奖励积分
            if ($_G['jameson_read']['ftjltrameid'] && $_G['jameson_read']['ftjljine']) {
                updatemembercount($_G['uid'],
                array($_G['jameson_read']['ftjltrameid'] => $_G['jameson_read']['ftjljine']),
                true, 'FTJ', $data['tid'], lang('plugin/jameson_read', 'fatiejiangli'));
            }
        }
        C::t('#jameson_read#jamesonread_colums')->clear_cache(array('mulu' . $data['book_id'], 'pidbytid' . $data['tid'], 'cid' . $data['tid'], 'bytid' . $data['tid']));
        C::t('#jameson_read#jamesonread_books')->clear_cache(array("bookinfo-".$data['book_id']."-".$_G['uid'], "bookinfo-".$data['book_id']."-0"));
        echo $_G['siteurl'].'plugin.php?id=jameson_read&contrl=touchauthor&act=bookedit&forward=zhangjieguanli&book_id=' . $data['book_id'] . '&j_id=' . $data['j_id'];
    }
    // 编辑章节
    public function editcolum()
    {
        global $_G;
        $authorinfo = C::t('#jameson_read#jamesonread_authors')->fetch($_G['uid']);
        if (!$authorinfo['allowedit']) {
            // 如果被禁止编辑章节
            showmessage(lang('plugin/jameson_read', 'wuquanbianjizhangjie'), dreferer());
        }
        $colum_id = intval($_GET['colum_id']); // 获取图书名称
        $tid      = intval($_GET['tid']);
        $pid      = C::t('#jameson_read#jamesonread_colums')->fetch_pid_bytid($tid);
        $bookinfo = DB::fetch_first('SELECT * FROM %t WHERE book_id=%d', array('jamesonread_books', $_GET['book_id']));
        if ($colum_id && $tid) {
            $tidarray          = C::t("forum_post")->fetch('tid:' . $tid, $pid);
            $cidarray          = C::t('#jameson_read#jamesonread_colums')->fetch($_GET['colum_id']);
            $jamesonread_title = $cidarray['subject'];
            $message = preg_replace("/[^\w_=\/]jameson_read/i",'',$tidarray['message']);
            $message = stripcslashes($message);
        } else {
            $jamesonread_title = lang('plugin/jameson_read', 'tianjiaxinzhangjie');
            $tidarray          = $cidarray          = array();
            $message = '';
        }
        $navtitle = ($cidarray?$cidarray['subject']:lang('plugin/jameson_read','tianjiaxinzhangjie')).'_'.$bookinfo['book_name'].'_'.lang('plugin/jameson_read','zuozhezhongxin').'_'.$_G['setting']['bbname'];
        include template("jameson_read:touch/authoreditcolum");
    }
}